package com.cuckoo.cuckoo_app2.service;

import android.content.Context;
import android.util.Log;

import com.cuckoo.cuckoo_app2.MyApplication;
import com.cuckoo.cuckoo_app2.business.Imp.PlatformBusinessImp;
import com.cuckoo.cuckoo_app2.business.PlatformBusiness;
import com.cuckoo.cuckoo_app2.business.SiteLinkBusiness;
import com.cuckoo.cuckoo_app2.dao.Platform;
import com.cuckoo.cuckoo_app2.dao.SiteLink;
import com.cuckoo.cuckoo_app2.business.Imp.SiteLinkBusinessImp;
import com.cuckoo.cuckoo_app2.dao.User;
import com.cuckoo.cuckoo_app2.thread.MonitorTaskTherad;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * 任务调度器 定时请求
 */
public class SchedulerService {

    private Context context;
    private SiteLinkBusiness siteLinkService;
    private PlatformBusiness platformBusiness;
    private ScheduledExecutorService scheduler;


    public SchedulerService(Context context) {
        this.context = context;
        siteLinkService = new SiteLinkBusinessImp();
        platformBusiness = new PlatformBusinessImp();
        scheduler = MyApplication.getInstances().getScheduler();
    }

    /**
     * 执行所有店铺的任务监控，通过开启新线程来异步处理。
     * 此方法首先获取所有平台的数据，然后根据平台ID获取对应的站点链接，
     * 构建一个映射关系，接着创建并启动与平台数量相等的线程，
     * 每个线程执行一个店铺的监控任务。
     */
    public void monitorTaskTherad() {
        // 查询当前是否VIP
        User user = MyApplication.getInstances().getUser();
        if (user == null || user.getIsVip() == 0 || user.getToken().isEmpty()) {
            Log.i("TEST", "当前应用未登录或不是会员");
            return;
        }

        // 获取所有平台数据
        List<Platform> platforms = platformBusiness.getWhereAll();
        if (platforms.size() <= 0) {
            return;
        }
        // 根据平台ID获取对应的站点链接列表
        List<String> ids = platforms.stream().map(Platform::getId).collect(Collectors.toList());
        List<SiteLink> siteLinks = siteLinkService.getByIdsAll(ids);

        // 建立平台ID到站点链接的映射，如果有重复ID则保留原有的站点链接
        Map<String, SiteLink> siteLinkMap = siteLinks.stream()
                .collect(Collectors.toMap(
                        SiteLink::getId, // 用SiteLink对象的ID作为Map的键
                        Function.identity(), // 直接使用SiteLink对象本身作为Map的值
                        (existing, replacement) -> existing // 在键冲突时保留原有的值
                ));

        // 启动线程
        int count = platforms.size();
        CountDownLatch latch = new CountDownLatch(count); // 假设你有100个任务

        for (int j = 0; j < platforms.size(); j++) {
            int i = j;
            scheduler.submit(() -> {
                Platform platform = platforms.get(i);
                SiteLink siteLink = siteLinkMap.get(platform.getId());
                MonitorTaskTherad monitorTaskTherad = new MonitorTaskTherad();
                Log.i("TEST", "TITLE:" + platform.getTitle());
                // 判断时间戳不等于空  且当前时间 小于 时间戳加上 间隔
                long currentTime = System.currentTimeMillis() / 1000;
                if (platform.getTaskTime() != null && platform.getTaskTime() > 0) {
                    if (currentTime < platform.getTaskTime() + siteLink.getWaitTime()) {
                        Log.i("TEST", "当前时间小于时间戳，跳过本次任务");
                        return;
                    }
                }
                // 获取当前时间戳秒
                platform.setTaskTime(currentTime);
                platformBusiness.updata(platform);

                // 为防止内存过大 使用单线程 循环
                try {
                    monitorTaskTherad.run(siteLink, platform);
                }catch (Exception e){
                    Log.e("TEST", "线程异常：" + e.getMessage());
                    scheduler.shutdownNow();
                    Thread.currentThread().interrupt(); // 保持中断状态
                } finally {
                    monitorTaskTherad = null;
                    platform = null;
                    siteLink = null;
                    latch.countDown();
                }
            });
        }

        try {
            latch.await(); // 等待所有任务完成
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        Log.i("TEST", "所有线程结束");

    }
}
